package ldkxingzhe.l365calendar.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.annotation.NonNull;

import ldkxingzhe.l365calendar.App;
import ldkxingzhe.l365calendar.activity.AlertActivity;

/**
 * 警告的一些工具类
 */
public class AlertUtil{
    @SuppressWarnings("unused")
    private static final String TAG = "AlertUtil";

    public static final int EXPIRED_GROUP_NOTIFICATION_ID = 0;
    private AlertUtil(){}

    /**
     * 创建一个AlarmManagerInterface
     */
    public static AlarmManagerInterface createAlarmManager(Context context){
        final AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        return new AlarmManagerInterface() {
            @Override
            public void set(int type, long triggerAtMills, PendingIntent operation) {
                // 并不需要精确， 无所了
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    mgr.setExact(type, triggerAtMills, operation);
                }else{
                    mgr.set(type, triggerAtMills, operation);
                }
            }

            @Override
            public void cancel(PendingIntent pendingIntent) {
                mgr.cancel(pendingIntent);
            }
        };
    }

    public static void set(@NonNull AlarmManagerInterface in, long triggerAtMills){
        createAlarmManager(App.applicationContext)
                .set(AlarmManager.RTC_WAKEUP, triggerAtMills, getPendingIntent(App.applicationContext));
    }

    /**
     * 退出此PendingIntent的定时器
     * @param context 上下文
     */
    public static void cancel(Context context){
        createAlarmManager(context).cancel(getPendingIntent(context));
    }

    /**
     * @param context 上下文， 最好是application的上下文
     * @return
     */
    private static PendingIntent getPendingIntent(Context context) {
        Intent intent = new Intent(App.applicationContext, AlertActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
}
